package com.cs.cslc.biz.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

/**
 * LocalCacheManagerConfig 内存缓存配置类.
 *
 * @author cs4380 https://gitee.com/xhbug_cs4380  cs4380@163.com
 * @version 1.0
 * @since 2024-7-24
 */
@Configuration
public class LocalCacheManagerConfig {

    /**
     * 案例1：不自动过期，页面维护数据更新该缓存
     */
    @Bean("xxx1CacheManager")
    @Primary
    public CacheManager xxx1CacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置缓存的最大容量为1000个条目
                .maximumSize(1000));
        return caffeineCacheManager;
    }

    /**
     * 案例2：过期时间设置为90分钟，一个半小时
     */
    @Bean("xxx2CacheManager")
    public CacheManager xxx2CacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(Caffeine.newBuilder()
                //  过期时间，90分钟
                .expireAfterWrite(90, TimeUnit.MINUTES)
                // 设置缓存的最大容量为1000个条目
                .maximumSize(10000));
        return caffeineCacheManager;
    }

//    使用案例
//    @Cacheable(cacheNames = "xxx2Cache", key = "#id", cacheManager = "xxx2CacheManager")
//    public JSONObject findWebConfig(String id) {
//        LambdaQueryWrapper<JSONObject> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(JSONObject::getWebKey, webKey);
//        return this.getOne(queryWrapper);
//    }

}
